package com.czkj.hwz.decorate.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.czkj.hwz.decorate.Activity.ClassifyActivity3;
import com.czkj.hwz.decorate.Activity.HomeDecorationActivity;
import com.czkj.hwz.decorate.Activity.SearchActivity;
import com.czkj.hwz.decorate.Activity.SelectActivity;
import com.czkj.hwz.decorate.Activity.SupervisorActivity;
import com.czkj.hwz.decorate.Activity.WorkerClassifyActivity;
import com.czkj.hwz.decorate.MyApp;
import com.czkj.hwz.decorate.R;
import com.czkj.hwz.decorate.adapter.TestFragmentAdapter;
import com.czkj.hwz.decorate.base.HttpUrl;
import com.czkj.hwz.decorate.bean.Enterprise;
import com.czkj.hwz.decorate.bean.Goods;
import com.czkj.hwz.decorate.bean.WorkerType;
import com.czkj.hwz.decorate.view.banner.BannerView;
import com.google.gson.Gson;

import org.xutils.x;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.finalteam.okhttpfinal.HttpCycleContext;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.JsonHttpRequestCallback;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Headers;

/**
 * 作者：lxm on 2017/11/7 16:08
 * 邮箱：18014168291@189.cn
 * 才智科技
 */
public class FirstFragment extends Fragment implements HttpCycleContext, View.OnClickListener {
    private static final String TAG = "FirstFragment";
    protected final String HTTP_TASK_KEY = "HttpTaskKey_" + hashCode();
    private List<WorkerType> workerTypeLists;
    private ArrayList<Enterprise> mEnterprises;
    private Context mContext;
    private BannerView mBanner;
    private TabLayout tabLayout;
    private TextView main_title;
    private RelativeLayout iv_classfy;
    private RelativeLayout iv_search;
    private ImageView Appointment_supervision;
    private ImageView iv_team;
    private ImageView iv_company;
    private List<View> viewList;
    private String imgUrlStr;
    private String[] imgUrl;
    private String areaStrInfo;
    private ArrayList<Goods> goodsList;
    private TestFragmentAdapter adapter;
    private String mEnterpriseListStr;
    private ViewPager viewPager;
    private MyApp myApp;
    private Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    bannerViewUrl(imgUrl);
                    main_title.setText(areaStrInfo);
                    initData();
                    break;
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_first,container,false);
        mBanner= (BannerView) view.findViewById(R.id.banner);
        tabLayout= (TabLayout) view.findViewById(R.id.tab);
        viewPager= (ViewPager) view.findViewById(R.id.viewpager);
        main_title= (TextView) view.findViewById(R.id.main_title);
        iv_classfy= (RelativeLayout) view.findViewById(R.id.iv_classfy);
        iv_search= (RelativeLayout) view.findViewById(R.id.iv_search);
        Appointment_supervision= (ImageView) view.findViewById(R.id.Appointment_supervision);
        iv_team= (ImageView) view.findViewById(R.id.iv_team);
        iv_company= (ImageView) view.findViewById(R.id.iv_company);
        iv_classfy.setOnClickListener(this);
        iv_search.setOnClickListener(this);
        Appointment_supervision.setOnClickListener(this);
        iv_team.setOnClickListener(this);
        iv_company.setOnClickListener(this);
        main_title.setOnClickListener(this);

        return view;
    }

    private void initData() {
        String[] titles=mEnterpriseListStr.split(",");
        adapter = new TestFragmentAdapter(getChildFragmentManager(), Arrays.asList(titles),mEnterprises);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void getIndexData() {
        RequestParams params=new RequestParams(this);
        params.addFormDataPart("longitude", "119.038657");
        params.addFormDataPart("latitude", "33.609279");
        HttpRequest.get(HttpUrl.INDEX_GET,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseJson(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });

    }

    private void parseJson(JSONObject jsonObject) {

        JSONArray bannerArray=jsonObject.getJSONArray("Banner");
        for (int i=0;i<bannerArray.size();i++) {
            imgUrl[i]=bannerArray.getString(i);
        }
        JSONObject areaInfo=jsonObject.getJSONObject("AreaInfo");
        areaStrInfo=areaInfo.getString("street");
        JSONArray mEnterpriseArray=jsonObject.getJSONArray("Enterprise");
        mEnterprises= (ArrayList<Enterprise>) mEnterpriseArray.toJavaList(Enterprise.class);
        JSONArray goodsArray=jsonObject.getJSONArray("Goods");
        goodsList= (ArrayList<Goods>) goodsArray.toJavaList(Goods.class);
        Log.d(TAG, "parseJson: "+mEnterprises);
        Log.d(TAG, "parseJson: "+goodsList);
        mEnterpriseListStr=mEnterprises.toString().replaceAll("\\[","").replaceAll("\\]","");
        myApp= (MyApp) getActivity().getApplication();
        myApp.setmEnterpriseList(mEnterprises);
        handler.sendEmptyMessage(0);
    }

    private void bannerViewUrl(String[] imgs) {
        viewList = new ArrayList<View>();
        for (int i = 0; i < imgs.length; i++) {
            final ImageView image = new ImageView(mContext);
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            //设置显示格式
            imgUrlStr = HttpUrl.BASE_URL + imgs[i];
            x.image().bind(image, imgUrlStr);
            viewList.add(image);
        }
        mBanner.startLoop(true);
        mBanner.setViewList(viewList);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getIndexData();
        getWorkerTypeList();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        imgUrl=new String[3];
        workerTypeLists=new ArrayList<>();
        myApp=new MyApp();
    }

    @Override
    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }
    private void getWorkerTypeList() {
        RequestParams params=new RequestParams(this);
        HttpRequest.get(HttpUrl.WORKER_TYPE,params,new JsonHttpRequestCallback(){
            @Override
            protected void onSuccess(JSONObject jsonObject) {
                super.onSuccess(jsonObject);
                parseTypelistJson(jsonObject);
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
            }
        });
    }
    private void parseTypelistJson(JSONObject jsonObject) {
        workerTypeLists.clear();
        JSONArray jsonArray=jsonObject.getJSONArray("result");
        for (int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObject1=jsonArray.getJSONObject(i);
            Gson gson=new Gson();
            WorkerType workType=gson.fromJson(jsonObject1.toJSONString(),WorkerType.class);
            Log.d(TAG, "parseJson: "+workType.toString());
            Log.d(TAG, "parseJson: "+workType.getId());
            workerTypeLists.add(workType);

        }
        if (workerTypeLists.get(0).getName().equals("全部工种")) {

        }else {
            WorkerType workerType=new WorkerType();
            workerType.setName("全部工种");
            workerType.setId(-1000);
            workerTypeLists.add(0,workerType);
        }
         myApp= (MyApp) getActivity().getApplication();
        myApp.setWorkerTypeLists(workerTypeLists);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.iv_classfy:
                intent=new Intent(getContext(),ClassifyActivity3.class);
                startActivity(intent);
                break;
            case R.id.iv_search:
                intent=new Intent(getContext(),SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.Appointment_supervision:
                intent=new Intent(getContext(),SupervisorActivity.class);
                intent.putExtra("mEnterprises",mEnterprises);
                startActivity(intent);
                break;
            case R.id.iv_team:
                intent=new Intent(getContext(),WorkerClassifyActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_company:
                intent=new Intent(getContext(), HomeDecorationActivity.class);
                startActivity(intent);
                break;
            case R.id.main_title:
                intent=new Intent(getContext(), SelectActivity.class);
                startActivityForResult(intent,200);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==2) {
            if (requestCode==200) {
                String cityName=data.getStringExtra("cityName");
                main_title.setText(cityName);
            }
        }
    }

    public static FirstFragment newInstance() {

        Bundle args = new Bundle();

        FirstFragment fragment = new FirstFragment();
        fragment.setArguments(args);
        return fragment;
    }
}
